package com.vim.common.aspect;

import com.vim.common.model.response.RestfulResponse;
import com.vim.common.utils.AccessObjectUtils;
import com.vim.common.thread.SysLoginLogThread;
import com.vim.common.thread.ThreadPool;
import com.vim.modules.web.model.SysLoginLog;
import com.vim.modules.web.model.SysUser;
import com.vim.modules.web.service.SysLoginLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LoginLogAspect {

    @Value("${env_test}")
    private boolean envTest;

    @Resource
    private SysLoginLogService sysLoginLogService;

    @Pointcut("@annotation(com.vim.common.annotation.SysLoginLogRecord)")
    public void sysLoginLog(){}

    @AfterReturning(returning = "ret", pointcut = "sysLoginLog()")
    public void afterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        RestfulResponse response = (RestfulResponse)ret;
        //登录成功并且非测试环境
        if(response.getCode() == RestfulResponse.DEFAULT_OK && !envTest){
            Subject subject = SecurityUtils.getSubject();
            if(subject != null && subject.isAuthenticated()){
                SysUser sysUser = (SysUser)subject.getPrincipal();
                SysLoginLog sysLoginLog = new SysLoginLog();
                sysLoginLog.setLoginAccount(sysUser.getLoginAccount());
                sysLoginLog.setClientIp(AccessObjectUtils.getIpAddress(request));
                sysLoginLog.setLoginTime(new Date());

                //开启线程
                ThreadPool threadPool = ThreadPool.getInstance();
                SysLoginLogThread thread = new SysLoginLogThread(sysLoginLogService, sysLoginLog);
                threadPool.executorService.execute(thread);
            }
        }
    }
}
